package com.wiscamp.ninechapters.tags.infrastructure.configuration;

import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

/**
 * 第三数据库配置类
 *
 * @author yifeng
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "tagsEntityManagerFactory",
        transactionManagerRef = "tagsTransactionManager",
        basePackages = {"com.wiscamp.ninechapters.tags.infrastructure.mappers"}) //设置Repository所在位置
public class TagsDatabaseConfig {
    @Bean(name = "tagsDataSource")
    @Qualifier("tagsDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.tags")
    public DataSource tagsDataSource() {
        System.out.println("Loading tags database configuration.");
        return DataSourceBuilder.create().build();
    }

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "tagsEntityManager")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        System.out.println("Loading tags database.");
        return Objects.requireNonNull(entityManagerFactory(builder).getObject()).createEntityManager();
    }

    @Bean(name = "tagsEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(tagsDataSource())
                .properties(getVendorProperties())
                .packages("com.wiscamp.ninechapters.tags.infrastructure.po") //设置实体类所在位置
                .persistenceUnit("tagsPersistenceUnit")
                .build();
    }

    private Map<String, String> getVendorProperties() {
        return jpaProperties.getProperties();
    }

    @Bean(name = "tagsTransactionManager")
    PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(entityManagerFactory(builder).getObject()));
    }
}
